import pandas as pd
import numpy as np
import statsmodels.api as sm
from statsmodels import regression, tools


def get_return(series):
    # 计算收益率：当期/上期
    df = pd.DataFrame(series).shift(1).join(pd.DataFrame(series), lsuffix='_last')
    ret = (df.iloc[:, 1] / df.iloc[:, 0]) - 1
    return ret


def get_cum_return(series):
    # 计算累计收益率：当期/初期
    s = pd.Series(series)
    cum_ret = s.apply(lambda x: x / s[0])
    return cum_ret


def get_max_drawdown(series):
    # 最大回撤
    i = np.argmax((np.maximum.accumulate(series) - series) / np.maximum.accumulate(series))  # 结束位置
    if i == 0:
        return 0
    j = np.argmax(series[:i])  # 开始位置
    return (series[j] - series[i]) / (series[j])


def get_sharpe_ratio(series, Ref):
    # 夏普比率
    return (np.mean(series) - Ref) / np.std(series)


def linreg(x, y):
    x_ = sm.add_constant(x)
    model = regression.linear_model.OLS(y, x_).fit()
    return model.params[0], model.params[1]


def get_alpha_beta(series, benchmark_series):
    #计算alpha/beta因子
    alpha, beta = linreg(series, benchmark_series)
    return alpha, beta
